package com.winapi.project.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winapi.project.common.ErrorCode;
import com.winapi.project.constant.OrderStatus;
import com.winapi.project.constant.StatusConstant;
import com.winapi.project.exception.BusinessException;
import com.winapi.project.mapper.OrderMapper;
import com.winapi.project.model.dto.orders.OrdersAddRequest;
import com.winapi.project.model.vo.OrderVO;
import com.winapi.project.service.InterfaceInfoService;
import com.winapi.project.service.OrderService;
import com.winapi.project.service.UserInterfaceInfoService;
import com.winapi.project.service.UserService;
import com.winapi.winapicommon.model.entity.InterfaceInfo;
import com.winapi.winapicommon.model.entity.Orders;
import com.winapi.winapicommon.model.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
* @author 张莹莹
* @description 针对表【order(订单表)】的数据库操作Service实现
* @createDate 2023-12-18 00:37:09
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders>
    implements OrderService{
@Resource
private OrderMapper orderMapper;
@Resource
private UserService userService;
@Resource
private UserInterfaceInfoService userInterfaceInfoService;
@Resource
private InterfaceInfoService interfaceInfoService;
    @Override
    public List<OrderVO> listTopBuyInterfaceInfo() {
        List<Orders> orderList=orderMapper.listTopBuyInterfaceInfo();
        List<OrderVO> orderVOList=new ArrayList<>();
        for (Orders order:orderList) {

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            orderVOList.add(orderVO);
        }
        return orderVOList;
    }

    /**
     * 添加订单
     * @param ordersAddRequest
     * @param request
     * @return
     */
    @Override
    public OrderVO addOrder(OrdersAddRequest ordersAddRequest, HttpServletRequest request) {
        //1.参数不为空
        if (ordersAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = ordersAddRequest.getUserId();
        Long interfaceId = ordersAddRequest.getInterfaceInfoId();
        Double price = ordersAddRequest.getPrice();
        Integer number = ordersAddRequest.getNumber();
        BigDecimal totalAmount = ordersAddRequest.getTotalAmount();

        if (userId == null || interfaceId == null || number ==null || totalAmount == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        if (number<=0 || totalAmount.compareTo(new BigDecimal(0)) < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //接口和用户存在
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        final InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceId);
        if(interfaceInfo==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口不存在");
        }

        // 后端校验订单总价格
        double temp = price * number;
        BigDecimal bd = new BigDecimal(temp);
        double finalPrice = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (finalPrice != totalAmount.doubleValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "价格错误");
        }

        //没有限制接口总库存这里是无限
////        2.判断接口调用库存是否足够
//        int interfaceStock = apiBackendService.getInterfaceStockById(interfaceId);
//        if (interfaceStock<=0 || interfaceStock - count<=0){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口库存不足");
//        }
//
////        3.扣减接口库存 远程调用实现
//        boolean updateStockResult = apiBackendService.updateInterfaceStock(interfaceId, count);
//        if (!updateStockResult){
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"扣减库存失败");
//        }

//        4.数据库保存订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddRequest, orders);
       orders.setName(interfaceInfo.getName());
       orders.setDescription(interfaceInfo.getDescription());
        //生成订单号
        String orderNum = generateOrderNum(userId);
        orders.setOrderNumber(orderNum);


        //添加订单号到数据库
        this.save(orders);
        //6.构造订单详情并回显
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
//        orderVO.setInterfaceInfoId(interfaceId);
//        orderVO.setUserId(userId);
//        orderVO.setOrderNumber(orderNum);
//
        orderVO.setNumber(number);
//        orderVO.setPrice(price);
        orderVO.setTotalAmount(totalAmount.doubleValue());
//        orderVO.setType(orders.getType());
        orderVO.setType(StatusConstant.NOT_PAY);//未支付
//        orderVO.setDescription(interfaceInfo.getDescription());
//        orderVO.setName(interfaceInfo.getName());
        DateTime date = DateUtil.date();
//        orderVO.setCreateTime(date);
        orderVO.setExpirationTime(DateUtil.offset(date, DateField.MINUTE, 30));

        return orderVO;
    }

    @Override
    public void updateStatusByOrderNo(String orderNo, Integer orderStatus) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderNumber", orderNo);

        Orders orders= new Orders();
        orders.setType(orderStatus);

        baseMapper.update(orders, queryWrapper);
    }

    @Override
    public List<Orders> getNoPayOrderByDuration(int minutes) {
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));

        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", OrderStatus.NOTPAY);
        queryWrapper.le("createTime", instant);

        List<Orders> orderInfoList = baseMapper.selectList(queryWrapper);

        return orderInfoList;
    }

    @Override
    public Orders getOrdersByOrderNumber(String orderNumber) {
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("orderNumber",orderNumber);
        Orders orders = orderMapper.selectOne(queryWrapper);
        return orders;
    }

    /**
     * 生成订单号
     *
     * @return
     */
    private String generateOrderNum(Long userId) {
        String timeId = IdWorker.getTimeId();
        String substring = timeId.substring(0, timeId.length() - 15);
        return substring + RandomUtil.randomNumbers(5) + userId;
    }

}




